package com.android.websms;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.telephony.SmsManager;

import com.android.webserver.fwapi.HTMLPage;
import com.android.webserver.fwapi.Request;

public class SendSMS extends HTMLPage
{
	public SendSMS(Context context, Request request)
	{
		super(context, request);
	}

	@Override
	protected boolean create(Object... objects)
	{
		if (request.getType() == Request.GET_REQUEST)
		{
			if (getGETParameter("json") != null)
				getJSON();
			else
				displayPage();
		}
		else
			sendSMS();
		return true;
	}

	private void getJSON()
	{
		if (getPOSTParameter("id") != null)
		{
			
		}
		else
		{
	JSONArray ja = new JSONArray();
			
			Cursor c = context.getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
							ContactsContract.CommonDataKinds.Phone._ID }, null, null,
					"DISPLAY_NAME");

			try
			{
				if (c.getCount() != 0)
					for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
					{
						String displayName = c.getString(0);
						Long id = c.getLong(1);
						JSONObject j = new JSONObject();
						j.put("name", displayName);
						j.put("id", id);
						ja.put(j);
					}
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}
			finally
			{
				c.close();
			}
			appendStaticHTMLContent(ja.toString());
		}
	}
	
	
	private void displayPage()
	{
		if (getGETParameter("json") != null)
		{
			JSONArray ja = new JSONArray();
			
			Cursor c = context.getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
							ContactsContract.CommonDataKinds.Phone._ID }, null, null,
					"DISPLAY_NAME");

			try
			{
				if (c.getCount() != 0)
					for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
					{
						String displayName = c.getString(0);
						Long id = c.getLong(1);
						JSONObject j = new JSONObject();
						j.put("name", displayName);
						j.put("id", id);
						ja.put(j);
					}
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}
			finally
			{
				c.close();
			}
			appendStaticHTMLContent(ja.toString());
			return;
		}
		
		
		appendHTMLContent(context.getString(R.string.Header),			new String[] { "WebSMS" });
	
		if (getGETParameter("id") != null)
		{
				Cursor c = context.getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
							ContactsContract.CommonDataKinds.Phone.NUMBER },
					ContactsContract.CommonDataKinds.Phone._ID + "=?",
					new String[] { getGETParameter("id") }, null);

			try
			{
				if (c.getCount() != 1)
					appendStaticHTMLContent("Error, unknown contact");
				else
				{
					c.moveToFirst();
					appendHTMLContent("<h3>Send SMS to $</h3>"
							+ "<form action=\"send\" method=\"post\"> "
							+ "<input type=\"hidden\" name=\"id\" value=\"$\"/>"
							+ "<textarea name=\"text\" ></textarea><br/>"
							+ "<input type=\"submit\" value=\"send\"/></form>", new String[] {
							c.getString(0), getGETParameter("id") });
				}

			}
			finally
			{
				c.close();
			}
		}
		else
		{
			appendStaticHTMLContent("<h1>WebSMS</h1>" +
							"<p style=\"font-style:italic; color:grey; font-family: serif;\">Click on a contact to send a message</p>");
					appendStaticHTMLContent(
							"<form method=\"GET\" action=\"\"><b>Search contact </b><input type=\"text\" name=\"search\"/></form>"		);
			Cursor c = context.getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
							ContactsContract.CommonDataKinds.Phone._ID }, null, null,
					"DISPLAY_NAME");

			try
			{
				if (c.getCount() == 0)
					appendHTMLContent("No contacts on this phone", null);
				else
				{
					for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
					{
						String displayName = c.getString(0);
						Long id = c.getLong(1);
						appendHTMLContent("<p><a href=\"/websms/send?id=$\">$</a></p>",
								new String[] { id.toString(), displayName });
					}
				}
			}
			finally
			{
				c.close();
			}
		}
		appendStaticHTMLContent(context.getString(R.string.Footer));
	}

	private void sendSMS()
	{
		Cursor c = context.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
						ContactsContract.CommonDataKinds.Phone.NUMBER },
				ContactsContract.CommonDataKinds.Phone._ID + "=?",
				new String[] { getPOSTParameter("id") }, null);

		String res = "";
		try
		{
			if (c.getCount() != 1)
				res = "Error, unknown contact";
			else
			{
				c.moveToFirst();
				String number = c.getString(1);
				SmsManager sms = SmsManager.getDefault();
				sms.sendTextMessage(number, null, getPOSTParameter("text"), null, null);
				res = "SMS Sent";
			}

		}
		finally
		{
			c.close();
		}
		appendHTMLContent(
				"<html><body><head>"
						+ "<title>Send SMS from your browser</title></head><body>$</body></html>",
				new String[] { res });
	}

}
